<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标签来源" prop="tagSource">
        <el-select v-model="queryParams.tagSource" placeholder="全部标签来源" clearable style="width:220px">
          <el-option label="AI自动标注" value="1" />
          <el-option label="人工标注" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否验证" prop="isVerified">
        <el-select v-model="queryParams.isVerified" placeholder="全部验证状态" clearable style="width:220px">
          <el-option label="未验证" value="0" />
          <el-option label="已验证" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" @click="batchVerify" :disabled="!hasVerifiableItems">一键认证</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" @click="batchUnverify" :disabled="!classifyList.length">一键未认证</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 数据列表 -->
    <div v-loading="loading" class="classify-list">
      <el-card v-for="(item, index) in classifyList" :key="item.id" shadow="hover" class="classify-item">
        <div class="item-header">
          <el-checkbox v-model="item.selected" @change="handleItemSelect" />
          <span class="item-number">序号: {{ (queryParams.pageNum - 1) * queryParams.pageSize + index + 1 }}</span>
          <div class="item-actions">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(item)" size="small">修改</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(item)" size="small">删除</el-button>
            <el-button
              size="small"
              :type="item.isVerified == 1 ? 'warning' : 'success'"
              @click="toggleVerify(item)"
            >
              {{ item.isVerified == 1 ? '取消认证' : '认证' }}
            </el-button>
          </div>
        </div>
        
        <div class="item-content">
          <div class="content-row">
            <div class="content-item">
              <label>主题ID:</label>
              <span>{{ item.topicId }}</span>
            </div>
            <div class="content-item">
              <label>标签:</label>
              <span>{{ getTagDisplayName(item.userTagId, item.tagName) }}</span>
            </div>
          </div>
          
          <div class="content-row">
            <div class="content-item full-width">
              <label>关键词:</label>
              <span class="keywords">{{ item.keywords }}</span>
            </div>
          </div>
          
          <div class="content-row">
            <div class="content-item">
              <label>标签来源:</label>
              <el-tag :type="item.tagSource == 1 ? 'info' : 'success'" size="small">
                {{ item.tagSource == 1 ? 'AI自动标注' : '人工标注' }}
              </el-tag>
            </div>
            <div class="content-item">
              <label>是否验证:</label>
              <el-tag :type="item.isVerified == 1 ? 'success' : 'warning'" size="small">
                {{ item.isVerified == 1 ? '已验证' : '未验证' }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-card>
      
      <el-empty v-if="!classifyList.length && !loading" description="暂无数据" />
    </div>
    
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 编辑对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="classifyRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="主题ID" prop="topicId">
          <el-input v-model="form.topicId" placeholder="请输入主题ID" />
        </el-form-item>
        
        <el-form-item label="标签分类" prop="tagCategory">
          <el-select v-model="form.tagCategory" placeholder="请选择标签分类" clearable @change="handleCategoryChange" style="width:220px">
            <el-option v-for="category in tagCategories" :key="category" :label="category" :value="category" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="标签名称" prop="userTagId">
          <el-select v-model="form.userTagId" placeholder="请选择标签" clearable filterable :disabled="!form.tagCategory" style="width:220px">
            <el-option v-for="tag in filteredTags" :key="tag.id" :label="tag.tagName" :value="tag.id" />
          </el-select>
          <div v-if="!form.tagCategory" class="form-hint">请先选择标签分类</div>
        </el-form-item>
        
        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="form.keywords" type="textarea" placeholder="请输入关键词，逗号分隔" />
        </el-form-item>
        
        <el-form-item label="标签来源" prop="tagSource">
          <el-select v-model="form.tagSource" placeholder="请选择标签来源" style="width:220px">
            <el-option label="AI自动标注" :value="1" />
            <el-option label="人工标注" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="是否验证" prop="isVerified">
          <el-select v-model="form.isVerified" placeholder="请选择验证状态" style="width:220px">
            <el-option label="未验证" :value="0" />
            <el-option label="已验证" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { 
  listClassify, 
  getClassify, 
  delClassify, 
  updateClassify, 
  batchVerifyApi,
  batchUnverifyApi
} from "@/api/classify/classify";
import { listTag } from "@/api/tag/tag";

const { proxy } = getCurrentInstance();

// 响应式数据
const classifyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const allTags = ref([]);
const tagCategories = ref([]);
const filteredTags = ref([]);
const searchFilteredTags = ref([]);

// 查询参数
const queryParams = ref({
  pageNum: 1, pageSize: 10, tagSource: null, isVerified: null, tagCategory: null
});

// 表单数据
const form = ref({
  id: null, topicId: null, tagCategory: null, userTagId: null,
  keywords: null, tagSource: null, isVerified: null
});

// 表单验证规则
const rules = {
  topicId: [{ required: true, message: "主题ID不能为空", trigger: "blur" }],
  tagCategory: [{ required: true, message: "请选择标签分类", trigger: "change" }],
  userTagId: [{ required: true, message: "请选择标签", trigger: "change" }]
};

// 计算属性：是否有可认证的项目
const hasVerifiableItems = computed(() => {
  return classifyList.value.some(item => item.isVerified != 1 && item.userTagId);
});

// 加载标签数据
function loadAllTags() {
  listTag().then(response => {
    allTags.value = response.rows || response.data || [];
    tagCategories.value = [...new Set(allTags.value.map(tag => tag.tagCategory).filter(Boolean))];
  });
}

// 处理分类变化
function handleCategoryChange(category) {
  filteredTags.value = category ? allTags.value.filter(tag => tag.tagCategory === category) : [];
  if (!form.value._isInitializing) form.value.userTagId = null;
}

// 处理搜索分类变化
function handleSearchCategoryChange(category) {
  searchFilteredTags.value = category ? allTags.value.filter(tag => tag.tagCategory === category) : [];
  queryParams.value.userTagId = null;
}

// 获取列表数据
function getList() {
  loading.value = true;
  const params = Object.fromEntries(
    Object.entries(queryParams.value).filter(([, value]) => value !== null && value !== '' && value !== undefined)
  );
  
  listClassify(params).then(response => {
    classifyList.value = response.rows.map(item => ({ ...item, selected: false }));
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    proxy.$modal.msgError("搜索失败，请重试");
  });
}

// 重置表单
function reset() {
  form.value = { id: null, topicId: null, tagCategory: null, userTagId: null, keywords: null, tagSource: null, isVerified: null };
  filteredTags.value = [];
  proxy.resetForm("classifyRef");
}

// 搜索和重置
const handleQuery = () => { queryParams.value.pageNum = 1; getList(); };
const resetQuery = () => {
  queryParams.value = { pageNum: 1, pageSize: 10, tagSource: null, isVerified: null, tagCategory: null };
  proxy.resetForm("queryRef");
  getList();
};

// 处理选择
function handleItemSelect() {
  const selectedItems = classifyList.value.filter(item => item.selected);
  ids.value = selectedItems.map(item => item.id);
  single.value = selectedItems.length !== 1;
  multiple.value = selectedItems.length === 0;
}

// 修改处理
function handleUpdate(row) {
  reset();
  const _id = row?.id || ids.value;
  
  getClassify(_id).then(response => {
    console.log('=== 修改按钮调试信息 ===');
    console.log('后端返回的数据:', response.data);
    console.log('form.value.userTagId:', response.data.userTagId, '类型:', typeof response.data.userTagId);
    console.log('form.value.tagName:', response.data.tagName, '类型:', typeof response.data.tagName);
    
    form.value = { ...response.data, _isInitializing: true, tagSource: Number(response.data.tagSource), isVerified: Number(response.data.isVerified) };
    
    console.log('allTags数据:', allTags.value);
    console.log('allTags第一个元素:', allTags.value[0]);
    
    // 根据userTagId找到对应的标签信息，确保类型匹配
    const selectedTag = allTags.value.find(tag => {
      const match = tag.id == form.value.userTagId || String(tag.id) === String(form.value.userTagId);
      console.log(`比较: tag.id=${tag.id}(${typeof tag.id}) vs userTagId=${form.value.userTagId}(${typeof form.value.userTagId}) = ${match}`);
      return match;
    });
    
    console.log('找到的标签:', selectedTag);
    
    if (selectedTag) {
      form.value.tagCategory = selectedTag.tagCategory;
      filteredTags.value = allTags.value.filter(tag => tag.tagCategory === selectedTag.tagCategory);
      console.log('设置的分类:', selectedTag.tagCategory);
      console.log('过滤后的标签:', filteredTags.value);
    } else {
      // 如果没有找到对应的标签，可能是null标签，清空分类
      form.value.tagCategory = null;
      filteredTags.value = [];
      console.log('未找到匹配的标签，清空分类');
    }
    
    nextTick(() => delete form.value._isInitializing);
    open.value = true;
    title.value = "修改内容标签关联";
  });
}

// 提交表单
function submitForm() {
  proxy.$refs["classifyRef"].validate(valid => {
    if (valid) {
      const { tagCategory, _isInitializing, ...submitData } = form.value;
      updateClassify(submitData).then(() => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
      });
    }
  });
}

// 删除处理
function handleDelete(row) {
  const _ids = row?.id || ids.value;
  proxy.$modal.confirm(`是否确认删除内容标签关联编号为"${_ids}"的数据项？`).then(() => {
    return delClassify(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  });
}

// 辅助方法
const cancel = () => { open.value = false; reset(); };
const getTagDisplayName = (userTagId, tagName) => tagName || userTagId || '未知标签';

// 实现toggleVerify方法
function toggleVerify(item) {
  const newStatus = item.isVerified == 1 ? 0 : 1;
  updateClassify({ id: item.id, isVerified: newStatus }).then(() => {
    item.isVerified = newStatus;
    proxy.$modal.msgSuccess(newStatus ? "已认证" : "已取消认证");
  });
}

// 一键认证
function batchVerify() {
  // 只认证未认证且有标签的
  const ids = classifyList.value.filter(item => item.isVerified != 1 && item.userTagId).map(item => item.id);
  if (!ids.length) {
    proxy.$modal.msgWarning("没有可认证的数据");
    return;
  }
  
  proxy.$modal.confirm(`确认认证选中的 ${ids.length} 条记录？`).then(() => {
    return batchVerifyApi(ids);
  }).then(() => {
    // 更新本地数据
    classifyList.value.forEach(item => {
      if (ids.includes(item.id)) {
        item.isVerified = 1;
      }
    });
    proxy.$modal.msgSuccess("一键认证成功");
  }).catch(() => {
    proxy.$modal.msgError("一键认证失败");
  });
}

// 一键未认证
function batchUnverify() {
  const ids = classifyList.value.map(item => item.id);
  if (!ids.length) {
    proxy.$modal.msgWarning("没有可操作的数据");
    return;
  }
  
  proxy.$modal.confirm(`确认取消认证所有 ${ids.length} 条记录？`).then(() => {
    return batchUnverifyApi(ids);
  }).then(() => {
    // 更新本地数据
    classifyList.value.forEach(item => {
      item.isVerified = 0;
    });
    proxy.$modal.msgSuccess("一键未认证成功");
  }).catch(() => {
    proxy.$modal.msgError("一键未认证失败");
  });
}

// 生命周期
onMounted(() => { loadAllTags(); getList(); });
</script>

<style scoped>
.classify-list { margin-bottom: 20px; }
.classify-item { margin-bottom: 12px; }
.item-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid #ebeef5; }
.item-number { font-weight: 500; color: #409eff; }
.item-actions { display: flex; gap: 8px; }
.item-content { display: flex; flex-direction: column; gap: 8px; }
.content-row { display: flex; gap: 20px; }
.content-item { display: flex; align-items: center; flex: 1; }
.content-item.full-width { flex: 1 1 100%; }
.content-item label { font-weight: 500; color: #606266; margin-right: 8px; min-width: 60px; }
.keywords { word-break: break-all; }
.form-hint { font-size: 12px; color: #909399; margin-top: 4px; }
@media (max-width: 768px) {
  .content-row { flex-direction: column; gap: 8px; }
}
.item-actions :deep(.el-button) {
  font-size: 16px;
  height: 38px;
  padding: 0 18px;
}
</style>